package chances.epg.data.ibatis;

import org.apache.ibatis.session.RowBounds;

public class PageRowBounds extends RowBounds {
	private long recordCount;
	private int pageSize;
	private int pageNo = 1;
	
	private int start;
	private int pageCount;
	private int lastPageSize;

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public final static PageRowBounds PAGE_DEFAULT = new PageRowBounds(1,
			Integer.MAX_VALUE);

	public PageRowBounds() {
		super();
	}

	public PageRowBounds(int pageNo, int pageSize) {
		this.pageSize = pageSize;
		this.pageNo = pageNo;
	}

	public PageRowBounds(int pageSize) {
		this.pageSize = pageSize;
	}

	public long getRecordCount() {
		return recordCount;
	}

	public void setRecordCount(long recordCount) {
		this.recordCount = recordCount;
		this.calculate();
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	@Override
	public int getOffset() {
		return RowBounds.NO_ROW_OFFSET;
	}
	
	/**
	 * 分页查询开始位置.
	 * @return
	 */
	public int getPageOffset() {
		return (this.pageNo-1)*this.pageSize+this.start;
	}

	 /**
     * 计算总页数.
     */
    public void calculate() {
        this.pageCount = (int) recordCount / pageSize;

        this.lastPageSize = (int) this.recordCount % this.pageSize;

        if (this.lastPageSize == 0 && pageCount != 0) {
            this.lastPageSize = this.pageSize;
        } else {
            this.pageCount++;
        }

        // 如果当前页超出总页数时，修正当前页
        /*
        if (this.pageNo > this.pageCount) {
            this.pageNo = this.pageCount;
        }
        */
    }
	@Override
	public int getLimit() {
		return this.pageSize;
	}

	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	public int getLastPageSize() {
		return lastPageSize;
	}

	public void setLastPageSize(int lastPageSize) {
		this.lastPageSize = lastPageSize;
	}
}
